<?php
declare(strict_types=1);
namespace Helper;
//https://alinlp.console.aliyun.com/overview
class Npl
{
    /**
     * 中文分词
     * @param $Text
     * @param int $OutType 0：大粒度，1：中粒度（默认），2：小粒度
     * @return array|false|mixed
     */
    public static function GetWsChGeneral($Text, $OutType=1)
    {
        $content = self::request("alinlp.cn-hangzhou.aliyuncs.com", [
            "ServiceCode" => "alinlp",
            "Text"=>$Text,
            "Action" => "GetWsChGeneral",
            "TokenizerId"=>"GENERAL_CHN",
            "OutType"=>$OutType,
            "Version" => "2020-06-29",
        ]);
        return $content['result'];
    }

    /**
     * 词性标注
     * @param $Text
     * @param int $OutType 0：大粒度，1：中粒度（默认），2：小粒度
     * @return array|false|mixed
     */
    public static function GetPosChGeneral($Text, $OutType=1)
    {
        $content = self::request("alinlp.cn-hangzhou.aliyuncs.com", [
            "ServiceCode" => "alinlp",
            "Text"=>$Text,
            "Action" => "GetPosChGeneral",
            "TokenizerId"=>"GENERAL_CHN",
            "OutType"=>$OutType,
            "Version" => "2020-06-29",
        ]);
        return $content['result'];
    }

    /**
     * 中心词提取
     * @param $Text
     * @return array|false|mixed
     */
    public static function GetKeywordChEcom($Text)
    {
        $content = self::request("alinlp.cn-hangzhou.aliyuncs.com", [
            "ServiceCode" => "alinlp",
            "Text"=>$Text,
            "Action" => "GetKeywordChEcom",
            "Version" => "2020-06-29",
        ]);
        return $content['result'];
    }

    /**
     * 命名实体识别
     * @param $Text
     * @return array|false|mixed
     */
    public static function GetNerChEcom($Text)
    {
        $content = self::request("alinlp.cn-hangzhou.aliyuncs.com", [
            "ServiceCode" => "alinlp",
            "Text"=>$Text,
            "Action" => "GetNerChEcom",
            "Version" => "2020-06-29",
        ]);
        return $content['result'];
    }

    /**
     * 智能文本分类
     * @param $Text
     * @return array|false|mixed
     */
    public static function GetTcChEcom($Text)
    {
        $content = self::request("alinlp.cn-hangzhou.aliyuncs.com", [
            "ServiceCode" => "alinlp",
            "Text"=>$Text,
            "Action" => "GetTcChEcom",
            "Version" => "2020-06-29",
        ]);
        return $content['result'];
    }

    /**
     * 情感分析
     * @param $Text
     * @return array|false|mixed
     */
    public static function GetSaChGeneral($Text)
    {
        $content = self::request("alinlp.cn-hangzhou.aliyuncs.com", [
            "ServiceCode" => "alinlp",
            "Text"=>$Text,
            "Action" => "GetSaChGeneral",
            "Version" => "2020-06-29",
        ]);
        return $content['result'];
    }



    /**
     * 词向量
     * @param $Text
     * @param int $Size
     * @param string $Type “word”表示将句子切成词 “char_unigram”表示将句子切成字 “char_bigram”表示将句子切成双字
     * @param string $Operation “none”给句子中的每个词一个表示 “max”用按维度取最大值的方式进行句子表示 “average”用按维度取平均的方式进行句子表示
     * @return array|false|mixed
     */
    public static function GetWeChGeneral($Text,$Size=50,$Type='word',$Operation='average')
    {
        $content = self::request("alinlp.cn-hangzhou.aliyuncs.com", [
            "ServiceCode" => "alinlp",
            "Text"=>$Text,
            'Size'=>$Size,
            'Type'=>$Type,
            'Operation'=>$Operation,
            "Action" => "GetWeChGeneral",
            "Version" => "2020-06-29",
        ]);
        return $content['result'];
    }

    /**
     * 生成签名并发起请求
     */
    public static function request($domain, $params, $security = false)
    {
        $apiParams = array_merge([
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureNonce" => uniqid(mt_rand(0, 0xffff).'', true),
            "SignatureVersion" => "1.0",
            "AccessKeyId" => _CONF('sms_ali_id'),
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
            "Format" => "JSON",
        ], $params);
        ksort($apiParams);
        $sortedQueryStringTmp = "";
        foreach ($apiParams as $key => $value) {
            $sortedQueryStringTmp .= "&" . self::encode($key) . "=" . self::encode($value);
        }
        $stringToSign = "GET&%2F&" . self::encode(substr($sortedQueryStringTmp, 1));
        $sign = base64_encode(hash_hmac("sha1", $stringToSign, _CONF('sms_ali_key') . "&", true));
        $signature = self::encode($sign);
        $url = ($security ? 'https' : 'http') . "://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";
        try {
            $content = self::fetchContent($url, $security);
            $data = xn_json_decode($content);
            return isset($data['Data']) ? xn_json_decode($data['Data']):[];
        } catch (\Exception $e) {
            xn_log($e->getMessage(), 'npl_error');
            return false;
        }
    }

    private static function encode($str)
    {
        $res = urlencode($str);
        $res = str_replace(['+', '*', '%7E'], ['%20', '%2A', '~'], $res);
        return $res;
    }

    private static function fetchContent($url, $s = true)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["x-sdk-client" => "php/2.0.0"]);
        curl_setopt($ch, CURLOPT_IPRESOLVE, 1);
        if ($s) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }

        $rtn = curl_exec($ch);
        if ($rtn === false) {
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);
        return $rtn;
    }
}